package cn.duxiaod.demo.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 信号量示例
 * 需要一次性拿一个许可的情况
 */
public class SemaphoreExample1 {
    private static final int threadCount = 550;
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(300);
        //一次只能运行的线程数量
        Semaphore semaphore = new Semaphore(20);
        for (int i = 0; i < threadCount; i++) {
            final int threadnum = i;
            threadPool.execute(()->{
                try {
                    //获取一个许可，所以可运行的线程数为20/1=20
                    semaphore.acquire(1);
                    test(threadnum);
                    //释放许可
                    semaphore.release(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        threadPool.shutdown();
        System.out.println("finish");
    }

    private static void test(int threadnum) throws InterruptedException {
        Thread.sleep(1000);
        System.out.println("threadnum：" + threadnum);
        Thread.sleep(1000);
    }
}
